package com.motherchild.admin.controller;

import com.motherchild.admin.dto.ProductDTO;
import com.motherchild.admin.service.ProductService;
import com.motherchild.admin.vo.CategoryVO;
import com.motherchild.admin.vo.PageVO;
import com.motherchild.admin.vo.ProductDetailVO;
import com.motherchild.common.ApiResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/products")
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping("/page")
    public ApiResponse<PageVO> getList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword
           ) {
        return ApiResponse.success(productService.getList(page, pageSize, keyword));
    }

    @GetMapping("/{id}")
    public ApiResponse<ProductDetailVO> getDetail(@PathVariable Integer id) {
        return ApiResponse.success(productService.getDetail(id));
    }

    @PostMapping("/addUpdate")
    public ApiResponse<?> add(@RequestBody ProductDTO productDTO) {
        if (productDTO.getId() != null){
            productService.update(productDTO.getId(), productDTO);
            return ApiResponse.success();
        }
        productService.add(productDTO);
        return ApiResponse.success();
    }

    @DeleteMapping("delete/{id}")
    public ApiResponse<?> delete(@PathVariable Integer id) {
        productService.delete(id);
        return ApiResponse.success();
    }

    @GetMapping("/status/{id}/{status}")
    public ApiResponse<?> updateStatus(@PathVariable Integer id, @PathVariable Integer status) {
        productService.updateStatus(id, status);
        return ApiResponse.success();
    }

    @PutMapping("/{id}/stock")
    public ApiResponse<?> updateStock(@PathVariable Integer id, @RequestParam Integer stock) {
        productService.updateStock(id, stock);
        return ApiResponse.success();
    }


    @GetMapping("/categories")
    public ApiResponse<List<CategoryVO>> getCategories() {
        List<CategoryVO> categories = productService.getCategories();
        return ApiResponse.success(categories);
    }

    @PostMapping("/upload")
    public ApiResponse<String> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam(required = false) Integer productId) {
        if (file.isEmpty()) {
            return ApiResponse.error(500, "文件为空");
        }

        try {
            // 指定文件保存路径
            String uploadDir = "D:/bisheCode/shangjiaduan/src/assets/";
            File directory = new File(uploadDir);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            // 获取文件名
            String fileName;
            if (productId == null) {
                fileName = UUID.randomUUID().toString() + ".jpg";
            } else {
                String image = productService.getImageById(productId);
                if (image == null || image.isEmpty()) {
                    fileName = UUID.randomUUID().toString() + ".jpg";
                } else {
                    fileName = image;
                }
            }
            // 构建文件路径
            Path filePath = Paths.get(uploadDir + fileName);
            // 检查文件是否存在，如果存在则删除
            File existingFile = new File(filePath.toString());
            if (existingFile.exists()) {
                existingFile.delete();
            }
            // 保存文件
            Files.write(filePath, file.getBytes());

            return ApiResponse.success("文件上传成功: " + fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return ApiResponse.error(500, e.getMessage());
        }
    }
} 